﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Encodings.Web;
using System.Text.Json;
using System.Threading.Tasks;

namespace UI.Tools
{

    static class JsonHelper
    {
        /// <summary>
        /// 格式化JSON字符串
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static string ToJsonString<T>(this T obj)
        {
            if (obj != null)
            {
                var setting = new JsonSerializerOptions
                {
                    WriteIndented = true,
                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                };
                return JsonSerializer.Serialize(obj, setting);
            }
            return string.Empty;
        }

        public static T ToObject<T>(this string jsonStr)
        {
            return JsonSerializer.Deserialize<T>(jsonStr);
        }

        /// <summary>
        /// 小驼峰格式序列化。
        /// </summary>
        /// <typeparam name="T">对象类型</typeparam>
        /// <param name="entity">类型对象</param>
        /// <returns></returns>
        public static string SerializeWithCamel<T>(this T entity)
        {
            // 小驼峰序列化
            var setting = new JsonSerializerOptions
            {
                PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            };
            return JsonSerializer.Serialize(entity, setting);
        }

        /// <summary>
        /// 小驼峰格式反序列化。
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static T DeserializeWithCamel<T>(this string str)
        {
            if (str != null)
            {
                // 小驼峰序列化
                var setting = new JsonSerializerOptions
                {
                    PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
                    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
                };
                return JsonSerializer.Deserialize<T>(str, setting);
            }
            else
            {
                return default(T);
            }
        }
    }
}
